# views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from titiaccount.app.user.models import TitiUser

from Crypto.Hash import MD5

def login(request):
    if request.method == 'GET':
        return render_to_response('user/login.html')
    if request.method == 'POST':

        md5 = MD5.new()
        md5.update(request.POST['password'])
        password = md5.hexdigest()

        query = TitiUser.gql("WHERE email = :1 And password = :2", request.POST['email'], password)
        if query.count() == 1:
            request.session['user'] = query.get()
            return HttpResponseRedirect('/')
        else:
            return render_to_response('user/login.html')

def logout(request):
    request.session['user'] = None
    return HttpResponseRedirect('/')

def new(request):
    if request.method == 'GET':
        return render_to_response('user/user.html', {})
    if request.method == 'POST':

        md5 = MD5.new()
        md5.update(request.POST['password'])
        password = md5.hexdigest()

        query = TitiUser.gql("WHERE email = :1 And password = :2", request.POST['email'], password)
        if query.count() == 1: # Wrong, the user has existed.
            return render_to_response('user/user.html', {'message': 'User has existed!'})
        else:
            user = TitiUser(email = request.POST['email'], first_name = request.POST['first_name'], last_name = request.POST['last_name'], password = password)
            user.put()
            return HttpResponseRedirect('/')

def edit(request):
    return render_to_response('account_new.html', {})
